package cn.hist.hfp.service;

import cn.hist.hfp.converter.ManagerConverter;
import cn.hist.hfp.entity.Manager;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.ManagerRepository;
import cn.hist.hfp.util.Encryption;
import cn.hist.hfp.vo.ManagerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ManagerService {

    private final
    ManagerRepository managerRepository;

    private final Encryption encryption;

    private final ManagerConverter managerConverter;

    @Autowired
    public ManagerService(ManagerRepository managerRepository, Encryption encryption, ManagerConverter managerConverter) {
        this.managerRepository = managerRepository;
        this.encryption = encryption;
        this.managerConverter = managerConverter;
    }

    public Manager create(Manager manager) {
        manager.setPassword(encryption.encodeByMd5(manager.getPassword()));
        return managerRepository.save(manager);
    }

    public Manager findOne(int id) {
        Optional<Manager> optionalManager = managerRepository.findById(id);
        if (optionalManager.isPresent()) {
            return optionalManager.get();
        }
        throw new ResourceNotFoundException();
    }

    public ManagerVO findOneVO(int id) {
        return managerConverter.convert(findOne(id));
    }

    public Manager findByLoginNameAndPassword(String loginName, String password) {
        return managerRepository.findByLoginNameAndPassword(loginName, encryption.encodeByMd5(password));
    }

    public ManagerVO findVOByLoginNameAndPassword(String loginName, String password) {
        return managerConverter.convert(findByLoginNameAndPassword(loginName, password));
    }

    public Manager update(Manager Manager) {
        return managerRepository.save(Manager);
    }

    public ManagerVO updateVO(Manager manager) {
        return managerConverter.convert(update(manager));
    }

    public void delete(int id) {
        Optional<Manager> optionalManager = managerRepository.findById(id);
        optionalManager.ifPresent(managerRepository::delete);
    }
}
